<?php

class Sections extends fvRoot implements iLogger {
    
    protected $currentEntity = '';
    
    function __construct () {
        $this->currentEntity = __CLASS__;
        parent::__construct(fvSite::$fvConfig->get("entities.{$this->currentEntity}.fields"), 
                            fvSite::$fvConfig->get("entities.{$this->currentEntity}.table_name"), 
                            fvSite::$fvConfig->get("entities.{$this->currentEntity}.primary_key", "id"));
    }
    
	public function validateTranslit_title($value) {
        $valid = (preg_match("/^[a-z_0-9]{3,}$/i", $value) > 0);
        $this->setValidationResult("translit_title", $valid, '"Название (транслит)" должно быть не менее 3-х символов и содержать только буквы латинского алфавита (в нижнем регистре) и подчеркивание.');
        $valid = $valid && (($count = SectionsManager::getInstance()->getCount('translit_title = ?', array($value))) == 0);
        if ($count > 0) {
            $this->setValidationResult("translit_title", $valid, '"Название (транслит)" должно быть уникальным');
        }

        return $valid;
    }
    
	function validateTitle($value) {
        $valid = (strlen($value) > 0);
        $this->setValidationResult("title", $valid);
        return $valid;
    }
    
	public function validateDiscount($value) {
        if (!is_numeric($value)){
			$valid = false;
			$message = 'Поле "Скидка" должно быть числом';
        }
        elseif ($value < 0) {
        	$valid = false;
			$message = 'Поле "Скидка" должно быть больше нуля';
        }
		elseif ($value > 100) {
        	$valid = false;
			$message = 'Поле "Скидка" не может быть больше 100';
        }
		else{
			$valid = true;
		}
        $this->setValidationResult('discount', $valid, $message);
        return $valid;
    }
    
    public function getLogMessage($operation) {
        $message = "Категория товара была ";
        switch ($operation) {
            case Log::OPERATION_INSERT: $message .= "создана ";break;
            case Log::OPERATION_UPDATE: $message .= "изменена ";break;
            case Log::OPERATION_DELETE: $message .= "удалена ";break;
            case Log::OPERATION_ERROR: $message = "Произошла ошибка при операции с записью ";break;
        }
        $user = fvSite::$fvSession->getUser();
        $message .= "в ".date("Y-m-d H:i:s").". Менеджер [".$user->getPk()."] " . $user->getLogin() . " (" . $user->getFullName() . ")";
        return $message;    
    }
    
    public function getLogName() {
        return $this->title;    
    }
    
    public function putToLog($operation) {
        $logMessage = new Log();
        $logMessage->operation = $operation;
        $logMessage->object_type = __CLASS__;
        $logMessage->object_name = $this->getLogName();
        $logMessage->object_id = $this->getPk();
        $logMessage->manager_id = (fvSite::$fvSession->getUser())?fvSite::$fvSession->getUser()->getPk():-1;
        $logMessage->message = $this->getLogMessage($operation);
        $logMessage->edit_link = fvSite::$fvConfig->get('dir_web_root')."sections/edit/?id=".$this->getPk();
        $logMessage->save();
    }
     
    public function getCountProducts() {
     	$stop = 1;
     	$result = array() ;
     	$params_tmp = array($this->getPk());
		do{
			$Sections = SectionsManager::getInstance()->getAll("parent_id in (".implode(',', $params_tmp).")");
			$params_tmp = array ();
			if (count($Sections)){
				foreach ($Sections as $Section){
					$params_tmp[] = $Section->getPk();
					$result = array_unique(array_merge($params_tmp, $result));
				}
			}
			else{
				$stop = 0;
			}
		} while ($stop!=0);
		$result[] = $this->getPk();
		$count = ProductsManager::getInstance()->getCount('category_id in ('.implode(',', $result).')');
		return $count;
     }
}

?>
